<template>
  <div class="tableRow">
    <el-row class="select-list" v-permission="'system:role:query'">
      <el-form :inline="true" ref="selectForm" :model="selectFormModel" :label-position="'right'"
               label-width="80px" size="mini">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="selectFormModel.roleName" placeholder="角色名称" style="width: 200px" clearable
                    @keyup.enter.native="onSearch"/>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="selectFormModel.roleKey" placeholder="权限字符" style="width: 200px" clearable
                    @keyup.enter.native="onSearch"/>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-select value="" v-model="selectFormModel.status" placeholder="角色状态" style="width: 200px">
            <el-option label="启用" value="0"/>
            <el-option label="停用" value="1"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" plain round @click="onSearch">搜索
          </el-button>
          <el-button type="warning" icon="el-icon-refresh" size="mini" plain round
                     @click="onRefreshSelectForm">重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-row>
    <el-row class="toolbar">
      <el-button type="primary" icon="el-icon-plus" size="mini" plain @click="handleAdd"
                 v-permission="'system:role:add'">
        新增
      </el-button>
      <el-button type="info" icon="el-icon-edit" :disabled="dialog.isBatchEditDisabled" size="mini" plain
                 @click="handleEdit" v-permission="'system:role:edit'"> 编辑
      </el-button>
      <el-button type="danger" icon="el-icon-delete" :disabled="dialog.isBatchRemoveDisabled" size="mini" plain
                 @click="handleBatchDelete" v-permission="'system:role:remove'"> 删除
      </el-button>
      <el-button type="warning" icon="fa fa-download" size="mini" plain @click="handleExport"
                 v-permission="'system:role:export'"> 导出
      </el-button>
    </el-row>
    <data-table ref="dataTable"
                :options="options"
                :operates="operates"
                :api="getRoleList"
                :columns="columns"
                :query="selectFormModel"
                @handle-selection-change="handleSelectionChange"
    />

    <el-dialog :title="dialog.title" :visible.sync="dialog.dialogFormVisible"
               :modal-append-to-body="false"
               @close="closeDialog"
               :destroy-on-close="false" width="600px">
      <el-form :model="roleModel" ref="roleForm" label-width="100px" :rules="roleFormRules" size="small">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleModel.roleName" placeholder="角色名称"/>
        </el-form-item>
        <el-form-item label="权限字符" prop="roleKey">
          <el-input v-model="roleModel.roleKey" placeholder="权限字符"/>
        </el-form-item>
        <el-form-item label="显示顺序" prop="roleSort">
          <el-input-number v-model="roleModel.roleSort" value="1" :min="1" label="显示顺序"/>
        </el-form-item>
        <el-form-item label="角色状态" prop="status">
          <el-switch v-model="roleModel.status" active-color="#13ce66" inactive-color="#ff4949"
                     active-text="正常"
                     inactive-text="停用"
                     active-value="0"
                     inactive-value="1"/>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input v-model="roleModel.remark" placeholder="备注" maxlength="100"/>
        </el-form-item>
        <el-form-item label="菜单权限" prop="treeData">
          <el-tree
              :data="dialog.treeData"
              show-checkbox
              node-key="id"
              ref="tree"
              :props="dialog.permissionProps">
          </el-tree>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialog.dialogFormVisible=false" size="medium">取 消</el-button>
        <el-button type="primary" @click="submitForm" size="medium">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script lang="ts">
import {Component, Ref, Vue} from 'vue-property-decorator';
import DataTable from '@/components/DataTable/DataTable.vue';
import {
  addRole,
  checkRoleKeyUnique,
  checkRoleNameUnique,
  exportRole,
  getRoleList,
  getRolePermissionTree,
  removeRole,
  updateRole
} from '@/api/role';
import {validateForm} from '@/utils';

@Component({
  components: {
    DataTable
  }
})
export default class Role extends Vue {
  private getRoleList: any = getRoleList;
  @Ref('dataTable') private dataTable: any;
  @Ref('selectForm') private selectForm: any;
  @Ref('roleForm') private roleForm: any;
  @Ref('tree') private tree: any;
  /*搜索框*/
  selectFormModel: any = {
    roleName: '',
    roleKey: '',
    status: ''
  };
  /*列信息*/
  columns: any = [
    {label: 'ID', prop: 'id', sortable: 'custom'},
    {label: '角色名称', prop: 'roleName', sortable: 'custom'},
    {label: '权限字符', prop: 'roleKey', sortable: 'custom'},
    {label: '显示顺序', prop: 'roleSort', sortable: 'custom'},
    {
      label: '角色状态', prop: 'status', sortable: 'custom', render: function (createElement, row) {
        if (row && row.row && row.row.status === '0') {
          return createElement('el-tag', {
                attrs: {
                  type: 'success'
                }
              }, ['正常']
          );
        } else if (row && row.row && row.row.status === '1') {
          return createElement('el-tag', {
                attrs: {
                  type: 'warning'
                }
              }, ['停用']
          );
        }
      }
    },
    {label: '创建时间', prop: 'createTime', sortable: 'custom', width: 160, showOverflowTooltip: true},
    {label: '创建者', prop: 'createBy', sortable: 'custom'},
    {label: '更新时间', prop: 'updateTime', sortable: 'custom', width: 160, showOverflowTooltip: true},
    {label: '更新者', prop: 'updateBy', sortable: 'custom'},
    {label: '备注', prop: 'remark', sortable: 'custom', showOverflowTooltip: true},
  ];

  // table 的参数
  options: any = {
    stripe: true, // 是否为斑马纹 table
    loading: false, // 是否添加表格loading加载动画
    highlightCurrentRow: true, // 是否支持当前行高亮显示
    multipleSelect: true, // 是否支持列表项选中功能
  };
  /*操作栏*/
  operates: any = {
    title: '操作',
    width: 'auto',
    fixed: 'right',
    list: [
      {
        label: '编辑',
        type: 'warning',
        icon: 'el-icon-edit',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'system:role:edit',
        method: (index, row) => {
          this.handleEdit(index, row);
        }
      },
      {
        label: '删除',
        type: 'danger',
        icon: 'el-icon-delete',
        plain: true,
        disabled: (index, row) => {
          return false;
        },
        permission: 'system:role:remove',
        method: (index, row) => {
          this.handleDelete(index, row);
        }
      }
    ]
  };
  dialog: any = {
    dialogFormVisible: false,
    title: '对话框',
    isEdit: false,
    isBatchEditDisabled: true,
    isBatchRemoveDisabled: true,
    formData: [],
    permissionProps: {
      children: 'children',
      label: 'label'
    }
  };

  roleModel: any = {
    roleName: '',
    roleKey: '',
    roleSort: '',
    status: 0,
    remark: '',
    treeData: []
  };

  roleFormRules: any = {
    roleName: [
      {required: true, message: '角色名称不能为空', trigger: ['blur', 'change']},
      {validator: this.validateRoleNameUnique, trigger: 'blur'}
    ],
    roleKey: [
      {required: true, message: '权限字符不能为空', trigger: ['blur', 'change']},
      {validator: this.validateRoleKeyUnique, trigger: 'blur'}
    ],
    roleSort: [
      {required: true, message: '显示顺序不能为空', trigger: ['blur', 'change']}
    ],
  };

  /*验证角色名称是否唯一*/
  validateRoleNameUnique(rule: any, value: any, callback: any) {
    checkRoleNameUnique({
      roleName: value,
      id: this.roleModel.id
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('角色名称已经存在'));
      }
    }).catch((err: any) => {
      console.log(err);
      callback(new Error('角色名称已经存在'));
    })
  }

  /*验证权限字符是否唯一*/
  validateRoleKeyUnique(rule: any, value: any, callback: any) {
    checkRoleKeyUnique({
      roleKey: value,
      id: this.roleModel.id
    }).then((res: any) => {
      if (res.data && res.data === '0') {
        callback();
      } else {
        callback(new Error('权限字符已经存在'));
      }
    }).catch((err: any) => {
      console.log(err);
      callback(new Error('权限字符已经存在'));
    })
  }

  /*新增*/
  handleAdd() {
    this.dialog.title = '新增角色';
    this.dialog.isEdit = false;
    getRolePermissionTree().then((response) => {
      if (response.data) {
        this.dialog.treeData = response.data.treeData;
        this.dialog.dialogFormVisible = true;
        this.$nextTick(() => {
          this.tree.setCheckedKeys([]);
        });
      }
    }).catch((e) => {
      console.log(e);
    });
  }

  /*编辑*/
  handleEdit(index: number, row: any) {
    this.dialog.title = '编辑角色';
    this.dialog.isEdit = true;

    this.roleModel = Object.assign({}, row || this.dialog.formData[0]);
    getRolePermissionTree(row || this.dialog.formData[0]).then((response) => {
      if (response.data) {
        this.dialog.treeData = response.data.treeData;
        this.dialog.dialogFormVisible = true;
        this.$nextTick(() => {
          if (response.data.checked && response.data.checked.length > 0) {
            response.data.checked.forEach((i, n) => {
              const node = this.tree.getNode(i);
              if (node.isLeaf) {
                this.tree.setChecked(node, true, false);
              }
            })
          }
        });
      }
    }).catch((e) => {
      console.log(e);
    });
  }

  /*删除*/
  handleDelete(index: number, row: any) {
    this.$confirm('确定要删除该角色？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      return removeRole({'ids': [row.id]});
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.log(e);
    });
  }

  /*批量删除*/
  handleBatchDelete() {
    //删除
    this.$confirm('确定要删除选定角色？', '警告', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    }).then(() => {
      const ids: Array<any> = [];
      this.dialog.formData.forEach((item, index) => {
        ids[index] = item.id;
      });
      return removeRole({'ids': ids});
    }).then((response: any) => {
      this.dataTable.refresh();
      this.$message.success(response.msg);
    }).catch((e) => {
      console.log(e);
    });
  }

  submitForm(): void {
    this.roleForm.validate((valid: boolean) => {
      if (valid) {
        if (this.dialog.isEdit) {
          //编辑
          this.roleModel.menuIds = this.tree.getCheckedKeys().concat(this.tree.getHalfCheckedKeys());//获取角色权限数组
          updateRole(this.roleModel).then((response: any) => {
            this.dataTable.refresh();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            validateForm(e.data, this.roleForm, this.roleFormRules);
          });
        } else {
          //新增
          this.roleModel.treeData = [];
          this.roleModel.menuIds = this.tree.getCheckedKeys().concat(this.tree.getHalfCheckedKeys());//获取角色权限数组
          addRole(this.roleModel).then((response: any) => {
            this.dataTable.refresh();
            this.reset();
            this.dialog.dialogFormVisible = false;
            this.$message.success(response.msg);
          }).catch((e) => {
            validateForm(e.data, this.roleForm, this.roleFormRules);
          });
        }
      }
    });
  }

  /*选中事件*/
  handleSelectionChange(val): void {
    if (val) {
      this.dialog.isBatchRemoveDisabled = val.length <= 0;
      this.dialog.isBatchEditDisabled = val.length !== 1;
    }
    this.dialog.formData = val;
  }

  /*导出excel*/
  handleExport(): void {
    this.$confirm('确定要导出当前查询的所有角色信息吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'info'
    }).then(() => {
      this.selectFormModel.pageNum = null;
      this.selectFormModel.pageSize = null;
      this.selectFormModel.orderByColumn = 'id';
      this.selectFormModel.isAsc = 'asc';

      return exportRole(this.selectFormModel);
    }).then((response: any) => {
      console.log(response);
      if (response && response.data) {
        (this as any).$download(response.data.fileName);
      }
    }).catch((e) => {
      console.log(e);
    });
  }

  /*搜索*/
  onSearch(): void {
    this.dataTable.refresh();
  }

  /*重置*/
  onRefreshSelectForm(): void {
    //恢复搜索默认信息
    this.selectForm.resetFields();
    this.onSearch();
  }

  /*重置表单*/
  reset(): void {
    this.roleModel = {
      roleName: '',
      roleKey: '',
      roleSort: '',
      status: 0,
      remark: '',
      treeData: [],
      checked: [],
    };
    (this as any).resetForm('roleForm');
  }

  /*关闭对话框*/
  closeDialog() {
    this.$nextTick(() => {
      this.reset();
    });
  }
}
</script>

<style scoped lang="scss">

</style>

